/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.threapool.executor;

import jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class JunitTest {
    private static Logger log = LoggerFactory.getLogger(JunitTest.class.getSimpleName());
    @Test
    public void poolTestExecutor() throws InterruptedException {
        // 自定义线程池的未捕获异常处理程序
        /*ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8,
                30, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadFactoryBuilder()
                        .setNameFormat("pool-%d")
                        .setUncaughtExceptionHandler((Thread t, Throwable e) -> {
                            log.error("pool happen exception, thread is {}", t, e);
                        }).build());*/
        ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8,
                30, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadFactoryBuilder().setNameFormat("pool-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy()
                        );
        // 设置全局的默认未捕获异常处理程序
 /*   static {
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            log.error("Thread {} got exception", thread, throwable);
        });
    }*/

      try {
          IntStream.rangeClosed(1,6).forEach(i-> {
              executor.execute(
                      () -> {
                          if (i == 3) {
                              log.info("throw execptions");
                              throw new RuntimeException("error");
                          }
                          log.info("doing i={}", i);
                      });
          });
      }catch (Exception e){
          log.info("catch execptions");
          e.printStackTrace();
      }
        executor.awaitTermination(1,TimeUnit.MINUTES);
    }


    @Test
    public void poolTestSubmit() throws InterruptedException {
        // 自定义线程池的未捕获异常处理程序
        ThreadPoolExecutor executor = new ThreadPoolExecutor(8, 8,
                30, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(),
                new ThreadFactoryBuilder()
                        .setNameFormat("pool-%d")
                        .setUncaughtExceptionHandler((Thread t, Throwable e) -> {
                            log.error("pool happen exception, thread is {}", t, e);
                        }).build());

       /* try {
            IntStream.rangeClosed(1,6).forEach(i-> {
                executor.execute(
                        () -> {
                            if (i == 3) {
                                log.info("throw execptions");
                                throw new RuntimeException("error");
                            }
                            log.info("doing i={}", i);
                        });
            });
        }catch (Exception e){
            log.info("catch execptions");
            e.printStackTrace();
        }*/
       List<Future<?>> result = IntStream.rangeClosed(1,6).mapToObj(i-> {
          return executor.submit(
                   () -> {
                       if (i == 3) {
                           log.info("throw execptions");
                           throw new RuntimeException("error");
                       }
                       log.info("doing i={}", i);
                   });
       }).collect(Collectors.toList());
       for (Future<?> future:result){
           try {
               future.get();
//               log.info("get future ={}", future.get());
           } catch (ExecutionException e) {
               log.info("catch error");
           }
       }
        executor.awaitTermination(1,TimeUnit.MINUTES);
    }

    // 设置全局的默认未捕获异常处理程序
    static {
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            log.error("Thread {} got exception", thread, throwable);
        });
    }

}
